<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>BabyNotes</title>
<meta name="viewport" content="width=320, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="data/webapp.css" type="text/css"/>
<link rel="stylesheet" href="data/skin_2.css" type="text/css" id="skin_2"/>
<link rel="stylesheet" href="data/skin_3.css" type="text/css" id="skin_3"/>
<link rel="stylesheet" href="data/skin_4.css" type="text/css" id="skin_4"/>

<script type="text/javascript" src="phonegap-1.2.0-min.js" charset="utf-8"></script>
<script type="text/javascript" src="phonegap-plus.js" charset="utf-8"></script>
<script type="text/javascript" src="xui-2.3.0.min.js" charset="utf-8"></script>
<script type="text/javascript" src="jsgraph-min.js" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
//Phone对象
var Phone = {
    //作者，版本信息
	'version':110,
	'version_des':'1.1.0',
	'appno':'300001951441', //MM的应用编号
	'author':'GuoJian',
	'site':'http://www.xiaoguo.me',
	'email':'xiaoguo.me@gmail.com',
	//页面
	'page':[],
	//记住上次的页面
	'lastPage':'#pHome',
	
	//设备的标识
	'uuid':'0',
	//Phonegap扩展插件Plus
	'app':null,
	'env':{}, //环境变量
	
	//宝宝的信息-默认值
	'baby':[{'_babyid':0,'name':'宝宝','sex':'男娃',
	        'birthday':getDateStr(0),
	        'hdimg':'bb.jpg','bgimg':'bg.jpg','skin':'blue'}],
	'babynum':1, //宝宝的个数
	'babyidx':0,  //当前的宝宝
	'babyupt':true, //宝宝信息修改了
	
	//成长数据
	'grow':[],
	'grownum':0,
	'growid':0,
	'growidx':-1,
	//里程碑
	'mtone':[],
	'mtonenum':0,
	'mtoneid':0,
	'mtoneidx':-1,
	//日记
	'diary':[],
	'diarynum':0,
	'diaryid':0,
	'diaryidx':-1,
	'diarypage':0, //页次
	'diarylimit':5, //每页记录
	'diaryupt':true //需要从头读取
};

//dom准备好了
x$.ready(function(){
    //设置皮肤
    setSkin( loadSkin() );
    
    //遍历页面
    x$('.page').each(function(ele,idx){
        a = "#"+ele.id;
        Phone.page[a] = x$(a);
    });
    //只对有uiTo属性的进行监视
    x$('li[uiTo]').click(function(){
        uito = this.getAttribute('uiTo');
        if(uito!=null)
        {
            if(uito.indexOf('#')==0){
                toPage(uito);
            }
        }
    });
    
    //遍历导航按钮
    x$('#nav_foot').find('li').click(function(){
        //alert(this.className);
        x$('#nav_foot').find('li').each(function(ele,idx){
            cn = ele.className.toString();
            if(cn.indexOf('_fcs')>0){
                ele.className = cn.substr(0,cn.length-4);
            }
        });
        //focus
        cn = this.className.toString();
        if(cn.indexOf('_fcs')<0){
            this.className = cn+"_fcs";
        }
    });
           
});

//Phonegap接口准备好了
document.addEventListener("deviceready", function(){
	console.log('>>deviceready');
	Phone.uuid = device.uuid;
	//扩展接口
	Phone.app = window.plugins.Plus;
	
	Phone.app.msg('欢迎使用宝宝成长日记!');
	//获取环境变量
	Phone.app.init(function(obj){
		Phone.env = obj;
	},null);
	//初始化数据库
	Phone.app.initDB(function(){
			console.log('>>initDB ok');
			toPage('#pHome');
		},function(){console.log('>>initDB error');}
	);
	
    //注册退出按钮
    document.addEventListener("backbutton", function(){
        navigator.notification.confirm('退出宝宝成长日记?', function(btn){
            if(btn==1){
                navigator.app.exitApp();
            }
        }, '退出', '确定,取消');
    }, false);

}, true); //end deviceready

//alert
function Alert(str){
    navigator.notification.alert(str, function(){}, '提示', '确定');    
}
function Confirm(str, func_yes, func_no){
    navigator.notification.confirm(str, function(btn){
        if( func_yes != null && func_yes != "undefined" && btn == 1 ){
            func_yes();
        }
        if( func_no != null && func_no != "undefined" && btn != 1 ){
            func_no();
        }        
    }, '确认', '是,否');    
}

//显示隐藏loading
function ShowLoad(b){
    x$('#load').setStyle('display', b ? 'block' : 'none');
}

//随机数
function getRand(){  
    return Math.random() * 10000 + Math.random() * 100;
}
//根据ID取dom
function $(id){
    return document.getElementById(id);
}
//补零
function addZero(n){
    return n<10 ? "0"+n : n.toString();
}
//得到日期字符串
function getDateStr(d,cn){
    //20110101
    if(d && d>10000000){ //
        var b = d.toString();
        if(arguments.length>1 )
            return b.substr(0,4)+"年"+b.substr(4,2)+"月"+b.substr(6,2)+"日";    
        else
            return b.substr(0,4)+"-"+b.substr(4,2)+"-"+b.substr(6,2); 
    }else{ //当前日期
        var d1 = new Date();
        if(arguments.length<=1)
            return d1.getFullYear()+"-"+addZero(d1.getMonth()+1)+"-"+addZero(d1.getDate());
        else
            return d1.getFullYear()+"年"+addZero(d1.getMonth()+1)+"月"+addZero(d1.getDate())+"日";
    }
}
//得到月日
function getMonthDay(d){
    if(d && d>10000000){ //
        var b = d.toString();
        return b.substr(4,2)+"月"+b.substr(6,2)+"日";
    }else{ //当前日期
        var d1 = new Date();
        return addZero(d1.getMonth()+1)+"月"+addZero(d1.getDate())+"日";
    }    
}
//得到日期时间字符串
function getDateTimeStr(d){
    var d1 = new Date();
    if(d<0){ //作为图片名称, 20111102120000
        return d1.getFullYear()+""+addZero(d1.getMonth()+1)+""+addZero(d1.getDate())+""+addZero(d1.getHours())+""+addZero(d1.getMinutes())+""+addZero(d1.getSeconds());
    }else{ //2011-11-12 00:00:00
        return d1.getFullYear()+"-"+addZero(d1.getMonth()+1)+"-"+addZero(d1.getDate())+" "+addZero(d1.getHours())+":"+addZero(d1.getMinutes())+":"+addZero(d1.getSeconds());
    }
};

//得到成长月份，根据生日计算, 从0开始
function getMonth(d){
    var bstr = Phone.baby[0].birthday.toString();
    var d1 = new Date(); //生日
    d1.setFullYear( bstr.substr(0,4) );
    d1.setMonth( bstr.substr(4,2)-1 );
    d1.setDate( bstr.substr(6,2) );
    
    var d2 = new Date();//传入的日期
    d = d.toString();
    d2.setFullYear( d.substr(0,4) );
    d2.setMonth( d.substr(4,2)-1 );
    d2.setDate( d.substr(6,2) );
    
    var d3 = (d2.getTime() - d1.getTime()) / (1000*24*3600);
    d3 = Math.floor(d3 / 30);
    console.log(d+">>"+bstr+">>"+d3);
    return d3;
            
};

//得到年龄-和生日或者当前时间比较比较
function getAge(a, b){
    var d1 = new Date();
    if( a!='undefined' && a>0 ){
        a = a.toString();
        d1.setFullYear( a.substr(0,4) );
        d1.setMonth( a.substr(4,2)-1 );
        d1.setDate( a.substr(6,2) );
    }
    //生日
    var d2 = new Date();
    c = Phone.baby[Phone.babyidx].birthday.toString();
    c = c.replace(new RegExp("-","g"),"");
    d2.setFullYear( c.substr(0,4) );
    d2.setMonth( c.substr(4,2)-1 );
    d2.setDate( c.substr(6,2) ); 
    //差值
    var days = d1.getDate() - d2.getDate() + 1;
    var months = d1.getMonth() - d2.getMonth();
    var years = d1.getFullYear() - d2.getFullYear();
    if((years<0)||((years==0)&&(months<0))||((years==0)&&(months==0)&&(days<=0)))
        return 'N/A';
    if( days<0 ){
        months--;
        var d0 = new Date();
        d0.setMonth(d0.getMonth()-1);
        var d0_ = d0.getMonth()+1;
        if( d0_==1||d0_==3||d0_==5||d0_==7||d0_==8||d0_==10||d0_==12 ){
            days += 31;
        }else if(d0_==4||d0_==6||d0_==9||d0_==11){
            days += 30;
        }else{
            d0_ = d0.getFullYear();
            if( (d0_%400==0)||((d0_%4==0)&&(d0_%100!=0)) ){
                days += 29;
            }else{
                days += 28;
            }
        }
    }
    if(months<0){  
        months = (months+12)%12;  
        years--;  
    }
    var str = '';
    if( years>0 ) str += years + "岁";
    if( months>0 ) str += months + "个月";
    if( days>0 ) str += days + "天";
    return str;
};

//当前显示的页面
function getCurPage(){
    var a = "#pHome";
    for(i in Phone.page){
        if(Phone.page[i].getStyle('display').toString() != 'none'){
            return i;
        }
    }
    return a;  
};

//返回上次的页面
function Back(){
    console.log("Back to page="+Phone.lastPage);
    toPage(Phone.lastPage);
};

//切换页面
function toPage(id){
    Phone.lastPage = getCurPage();
    console.log("last page="+Phone.lastPage);
    
    pageChange(id);
    var chd = false;
	for(i in Phone.page)
	{
	    if(id == i){
	        Phone.page[i].setStyle('display', 'block');
	        chd = true;
	    }
	    else
	        Phone.page[i].setStyle('display', 'none');
	}
	if(!chd && $('pHome')){
	    toPage('#pHome');
	}
};

//页面切换了
function pageChange(id){
	if(id=='#pBaby' || id=='#pGrowAdd' || id=='#pMToneAdd' || id=='#pDiaryAdd' ){
		setFootNav('none');
	}else{
		setFootNav('block');
	}
	console.log('pageChange to '+id);
    var idx = Phone.babyidx;
    //首页
    if(id=='#pHome' )
    {
        //更新宝宝的信息
        if( Phone.babyupt ){
            console.log('Phone.babyupt true');
				//查询宝宝信息
				Phone.app.selDB("info","",function(q){
					var query = eval(q);
					var num = query.length;
					//还没有，跳转到添加页面
					if( num==0 ){
					    restore(function(){
    					    Phone.app.msg('请添加宝宝的信息');
    					    toPage('#pBaby');					        
					    });
					    return;			
					}else{
					    Phone.baby = query;
					    Phone.babynum = num;
					    Phone.babyupt = false;
					    
                        x$('#bbName').html(Phone.baby[idx].name+","+Phone.baby[idx].sex);
                        var b = Phone.baby[idx].birthday; //20111234
                        x$('#bbBir').html("生日"+b.substr(0,4)+"年"+b.substr(4,2)+"月"+b.substr(6,2)+"日");
                        x$('#bbAge').html('健康成长'+getAge());
                        x$('#bbImg').setStyle("background-image","url("+Phone.baby[idx].hdimg+"?"+getRand()+")");
                        
                        console.log('baby update ok');
                        getHomeInfo(idx);
					}					
				},function(){console.log('>>selDB error');}
			);            
        }else{
            getHomeInfo(idx);
        }
    }
    //宝宝信息编辑页
    else if( id=='#pBaby' )
    {
        x$('#iptName').attr('value', Phone.baby[idx].name );
        x$('#iptSex').attr('value', Phone.baby[idx].sex );
        x$('#iptBir').attr('value', getDateStr(Phone.baby[idx].birthday) );
        x$('#imgSrc').attr('src', Phone.baby[idx].hdimg);
    }
    //成长数据
    else if( id=='#pGrow' )
    {
        ShowLoad(1);
			//查询所有记录
			var bid = Phone.baby[idx]._babyid;
			Phone.app.selDB("grow","_babyid="+bid+" order by addtime desc",function(q)
			{
					Phone.grow = eval(q);
					Phone.grownum = Phone.grow.length;
					var ul = $("grow_tab2");
                    var t=ul.childNodes.length;
                    for(i=0;i<t;i++)
                        ul.removeChild(ul.childNodes[0]);					
					for(i=0;i<Phone.grownum;i++)
					{
					    var li = document.createElement("li");
					    li.className = "li_ico grow_ico";
					    li.innerHTML = "<img src='"+Phone.grow[i].imgurls+"'/>";
					    ul.appendChild(li);
					    
					    var li2 = document.createElement("li");
					    li2.className = "li_cont";
					    li2.setAttribute("onclick", "showGrow("+Phone.grow[i]._growid+");"); 
					    var txt = "<h1><span>"+ getAge(Phone.grow[i].addtime)+"</span>"+getDateStr(Phone.grow[i].addtime)+"</h1><p>";
					    var n=0;
					    if(Phone.grow[i].height>0){ txt += "身高"+Phone.grow[i].height+"厘米 "; n++;}
					    if(Phone.grow[i].weight>0){ txt += "体重"+Phone.grow[i].weight+"斤 "; n++;}
					    if(Phone.grow[i].head>0){if(n==2) txt +="<br/>"; txt += "头围"+Phone.grow[i].head+"厘米 "; n++;}
					    if(Phone.grow[i].chest>0){if(n==2) txt +="<br/>"; txt += "胸围"+Phone.grow[i].chest+"厘米 ";n++;}
					    li2.innerHTML = txt+"</p>";
					    ul.appendChild(li2);
					}
					//绘制成长曲线
					DrawGrowGraph();
					ShowLoad(0);				
				},function(){ShowLoad(0);console.log('>>selDB error');}
			);        
    }
    //添加成长记录
  	else if ( id=='#pGrowAdd' )
  	{
  	    ;
  	}
  	//里程碑
  	else if( id=='#pMTone' )
  	{
  	    ShowLoad(1);
			//查询所有记录
			var bid = Phone.baby[idx]._babyid;
			Phone.app.selDB("Milestone","_babyid="+bid+" order by addtime desc",function(q)
			{
					Phone.mtone = eval(q);
					Phone.mtonenum = Phone.mtone.length;
					var ul = $("mtone_list");
                    var t=ul.childNodes.length;
                    for(i=0;i<t;i++)
                        ul.removeChild(ul.childNodes[0]);					
					for(i=0;i<Phone.mtonenum;i++){
					    var li = document.createElement("li");
					    li.className = "li_ico mtone_ico";
					    li.innerHTML = "<img src='"+Phone.mtone[i].imgurls+"'/>";
					    ul.appendChild(li);					    
					    
					    var li2 = document.createElement("li");
					    li2.className = "li_cont";
					    li2.setAttribute("onclick", "showMTone("+Phone.mtone[i]._mtoneid+");"); 
					    txt = "<h1><span>"+ getAge(Phone.mtone[i].addtime)+"</span>"+getDateStr(Phone.mtone[i].addtime)+"</h1><p>";
					    txt += Phone.mtone[i].desc;
					    li2.innerHTML = txt+"</p>";
					    ul.appendChild(li2);
					}	
					ShowLoad(0);			
				},function(){ShowLoad(0);console.log('>>selDB pMTone error');}
			);     	    
  	}
    //添加里程碑
  	else if ( id=='#pMToneAdd' )
  	{
  	    ;
  	}  
  	//日记
  	else if( id=='#pDiary' )
  	{
  	    if( Phone.diaryupt )
  	        moreDiary();  	    
  	}
    //添加日记
  	else if ( id=='#pDiaryAdd' )
  	{
  	    ;
  	}    	 
};

//更新首页的概况
function getHomeInfo(i){
    //里程碑
    var bid = Phone.baby[i]._babyid;
    sql1 = "select _mtoneid,addtime,desc from Milestone where _babyid="+bid+" order by addtime desc limit 1";
    Phone.app.queryDB(sql1,function(q1){
        var qy1 = eval(q1);
        if(qy1.length >0){
            x$('#bbM').html( qy1[0].desc );
            x$('#bbMt').html( getMonthDay(qy1[0].addtime) );
            x$('#bbM').attr('onclick', 'showMTone('+qy1[0]._mtoneid+')');
        }
      },
      function(){db_end = true;alert('queryDB Milestone error');}
    );
    //日记
    sql2 = "select _diaryid,addtime,content from Diary where _babyid="+bid+" order by addtime desc limit 1";
    Phone.app.queryDB(sql2,function(q2){
        var qy2 = eval(q2);
        if(qy2.length >0){
            x$('#bbD').html( qy2[0].content );
            x$('#bbDt').html( getMonthDay(qy2[0].addtime) );
            x$('#bbD').attr('onclick', 'showDiary('+qy2[0]._diaryid+')');
        }
      },
      function(){db_end = true;alert('queryDB Diary error');}
    );

    //身高
    sql3 = "select _growid,addtime,height from Grow where _babyid="+bid+" and height>0 order by addtime desc limit 1";
    Phone.app.queryDB(sql3,function(q3){
        var qy3 = eval(q3);
        if(qy3.length >0){
            x$('#bbH').html( qy3[0].height+"厘米" );
            x$('#bbHt').html( getMonthDay(qy3[0].addtime) );
            x$('#bbH').attr('onclick', 'showGrow('+qy3[0]._growid+')');
        }
      },
      function(){db_end = true;alert('queryDB Grow error');}
    );    
    //体重
    sql4= "select _growid,addtime,weight from Grow where _babyid="+bid+" and weight>0 order by addtime desc limit 1";
    Phone.app.queryDB(sql4,function(q4){
        var qy4 = eval(q4);
        if(qy4.length >0){
            x$('#bbW').html( qy4[0].weight+"斤" );
            x$('#bbWt').html( getMonthDay(qy4[0].addtime) );
            x$('#bbW').attr('onclick', 'showGrow('+qy4[0]._growid+')');
        }
      },
      function(){db_end = true;alert('queryDB Grow error');}
    ); 
    //头围
    sql5 = "select _growid,addtime,head from Grow where _babyid="+bid+" and head>0 order by addtime desc limit 1";
    Phone.app.queryDB(sql5,function(q5){
        var qy5 = eval(q5);
        if(qy5.length >0){
            x$('#bbHd').html( qy5[0].head+"厘米" );
            x$('#bbHdt').html( getMonthDay(qy5[0].addtime) );
            x$('#bbHd').attr('onclick', 'showGrow('+qy5[0]._growid+')');
        }
      },
      function(){db_end = true;alert('queryDB Grow error');}
    ); 
    //胸围
    sql6 = "select _growid,addtime,chest from Grow where _babyid="+bid+" and chest>0 order by addtime desc limit 1";
    Phone.app.queryDB(sql6,function(q6){
        var qy6 = eval(q6);
        if(qy6.length >0){
            x$('#bbC').html( qy6[0].chest+"厘米" );
            x$('#bbCt').html( getMonthDay(qy6[0].addtime) );
            x$('#bbC').attr('onclick', 'showGrow('+qy6[0]._growid+')');
        }
      },
      function(){alert('queryDB Grow error');}
    );               
};

//分享
function share(id_day, subject, id_cont, id_img){
    var img = $(id_img).src.toString(); //console.log(img+"/"+img.indexOf("none.png"));
    var typ = 0;
    var cont = x$("#"+id_day).html()+","+x$("#"+id_cont).html()+"--宝宝成长日记";
    if( img.indexOf("none.png")>=0 ){
        Phone.app.shareText(subject, cont, null,null);
    }else{
        navigator.notification.confirm('选择分享数据的类型', function(btn){
                if(btn==1) Phone.app.shareText(subject, cont, null,null);
                else Phone.app.sharePic(img, null, null);
            }, '分享', '文本,图像');        
    }
};

//是否显示底部导航
function setFootNav(d){
	x$('#nav_foot').setStyle('display', d);
};

//选择生日
function getBirthday(e){
    Phone.app.datePicker(0,0,0,function(rlt){
        e.value = rlt.text;
    },null);
};
  
//选择性别
function getSex(e){
    navigator.notification.confirm('请选择宝宝的性别',function(btn){
        if(btn==1)
            e.value = '男娃';
        else
            e.value = '女娃';
            
    },'性别','男娃,女娃');
};

//选择头像
function getHeadimg(e){
    Phone.app.getPic(0, function(rlt){
        img = Phone.env.imgsmalldir + "/hd_"+ Phone.babyidx +'.jpg.s';
        console.log(img);
        Phone.app.cropPic(rlt.URI, img,
        function(){
            img += "?"+getRand();
            x$('#imgSrc').attr('src', img);
            
        }, function(){alert('error2');} );
    },function(){alert('error');});    
};

//选择或者照相
function getPic(tp,id){
    tstr = getDateTimeStr(-1);
    imgto = Phone.env.imgdir + "/baby"+ tstr +'.jpg';
    cropto = Phone.env.imgsmalldir + "/baby"+ tstr +'.jpg.s';
    console.log(imgto+";"+cropto);
    Phone.app.getPic(tp, function(rlt){
        //复制
        Phone.app.copy(rlt.URL,imgto,function(){
            x$(id).attr('src', imgto);
            Phone.app.msg('请您设置缩略图');
            //剪裁小图
            Phone.app.cropPicOpt(rlt.URL, cropto,{'outputX':64,'outputY':64},
            function(){
                x$(id+'Small').attr('src', cropto);
            }, function(){alert('error getPic2');} );            
        },function(){alert('copy error!');});
    },function(){alert('error getPic1');});      
};

//保存宝宝信息
function saveBaby(){
    var v1 = x$('#iptName').attr('value').toString();
    if(v1.length==0){
        Alert("请输入宝宝的姓名!");
        return;
    }
    var v2 = x$('#iptBir').attr('value').toString().replace(new RegExp("-","g"),"");
    var v3 = x$('#iptSex').attr('value').toString();
    var v4 = x$('#imgSrc').attr('src').toString();
    if(v4.indexOf('?')>0)
        v4 = v4.substr(0,v4.indexOf('?')); //xxx.jpg?123
    var vals = "'"+v1+"',"+v2+",'"+v3+"','"+v4+"'";
    console.log(vals);
    var i = Phone.babyidx;
    if( Phone.baby[i]._babyid <= 0 ){ //新建
        console.log('Add baby');
        Phone.app.newDB("info",vals,function(){
            console.log('>>newDB ok');
            Phone.babyupt = true;
            toPage('#pHome');
        },function(){console.log('>>newDB error');}
        );        
    }else{
        console.log('Edit baby'); //编辑
        var sql = "UPDATE Info set name='"+v1+"',birthday="+v2+",sex='"+v3+"',hdimg='"+v4+"' WHERE _babyid="+Phone.baby[i]._babyid;
        Phone.app.queryDB(sql, function(){
            console.log('>>editDB ok');
            Phone.babyupt = true;
            toPage('#pHome');
        },function(){console.log('>>editDB error');}
        );         
    }	    
};

//返回修改宝宝信息
function abortBaby(){
    if(Phone.baby._babyid<=0){
        Alert('请输入宝宝的信息!');
    }else{
        toPage('#pHome');
    }
};

//切换成长信息Tab
function growtab(i){
    for(c=1;c<=3;c++){
        x$('#gnav'+c).removeClass('fcs');
        x$('#gnav'+c).removeClass('nor');
        x$('#grow_tab'+c).setStyle("display","none");
        if(c==i){
            x$('#gnav'+c).addClass('fcs');
            x$('#grow_tab'+c).setStyle("display","block");
        }else{
            x$('#gnav'+c).addClass('nor');
        }
    }
};

//显示成长信息
function showGrow(id){
    Phone.growid = id;
    Phone.app.selDB('grow','_growid='+id,function(q){
        var qy = eval(q);
        i=0;
      	$('iptGday').value = getDateStr(qy[i].addtime);
      	$('iptHt').value = qy[i].height;
      	$('iptWt').value = qy[i].weight;
      	$('iptHd').value = qy[i].head;
      	$('iptCt').value = qy[i].chest;
      	$('imgGrow').src = qy[i].imgurl;
      	$('imgGrowSmall').src = qy[i].imgurls;         
        
        console.log("showGrow id="+id);
        toPage('#pGrowAdd');    
    },function(){alert('selDB grow error!');}
    );    
}
//新建成长信息
function AddGrow(){
    Phone.growid = 0;
    $('iptGday').value = getDateStr(0);
    $('iptHt').value = '0';
    $('iptWt').value = '0';
    $('iptHd').value = '0';
    $('iptCt').value = '0';
    $('imgGrow').src = "none.png";
    $('imgGrowSmall').src = "none.png";     
    toPage('#pGrowAdd');
};

//保存成长信息
function saveGrow(){
     var idx = Phone.babyidx;
     
    var v1 = x$('#iptGday').attr('value').toString().replace(new RegExp("-","g"),"");
    var v2 = x$('#iptHt').attr('value');
    var v3 = x$('#iptWt').attr('value');
    var v4 = x$('#iptHd').attr('value');
    var v5 = x$('#iptCt').attr('value');
    var img1 = x$('#imgGrow').attr('src');
    var img2 = x$('#imgGrowSmall').attr('src');
    
    var vals = Phone.baby[idx]._babyid+","+v1+",'"+img1+"','"+img2+"',"+v2+","+v3+","+v4+","+v5;
    console.log(vals);
    
    var gid = Phone.growid;
    if( gid <= 0 ){ //新建
        console.log('Add grow');
        Phone.app.newDB("grow",vals,function(){
            console.log('>>newDB ok');
            toPage('#pGrow');
        },function(){console.log('>>newDB error');}
        );        
    }else{ //编辑
        var sql = "UPDATE Grow set addtime="+v1+",imgurl='"+img1+"',imgurls='"+img2+"',height="+v2+",weight="+v3+",head="+v4+",chest="+v5;
        sql += " WHERE _growid="+gid;
        Phone.app.queryDB(sql, function(){
            console.log('>>editDB Grow ok');
            toPage('#pGrow');
        },function(){console.log('>>editDB Grow error');}
        );         
    }    
};

//绘制成长曲线
function DrawGrowGraph()
{
    var opts = {
        type: "bar",
        barWidth: 0.9,
        title: "身高曲线图",
        canvasName: "grow_canvas1",
        vstart: 0,
        vfinish: 100,
        vstep: 20,
        showkey:false
    };
    var idx1=0;
    var graph1 = new Graph(opts);
    graph1.lastSeries.name = "身高(厘米)";  
    
    opts.title = '体重曲线图';
    opts.canvasName = 'grow_canvas2';
    opts.vfinish = 50;
    opts.vstep = 10;
    var idx2 = 0;
    var graph2 = new Graph(opts);
    graph2.lastSeries.name = "体重(斤)";    
     
    //for(i=0; i<Phone.grownum; i++)
    for(i=Phone.grownum-1; i>=0; i--)
    {
        val = Phone.grow[i].height;
        if(val>0){
             //getMonth(Phone.grow[i].addtime);
            graph1.addPoint(idx1, val,'');
            idx1++;
        }
        val = Phone.grow[i].weight;
        if(val>0){
             //getMonth(Phone.grow[i].addtime);
            graph2.addPoint(idx2, val,'');
            idx2++;
        }        
    }
    if( idx1>0 && idx1<5 ){
        graph1.addPoint(5, 0,'');
    }
    if( idx2>0 && idx2<5 ){
        graph2.addPoint(5, 0,'');
    } 
    jsgraph_begin();
}

//显示里程碑信息
function showMTone(id){
    Phone.mtoneid = id;
    Phone.app.selDB('Milestone','_mtoneid='+id,function(q){
        var qy = eval(q);
        i=0;
      	$('iptMday').value = getDateStr(qy[i].addtime);
      	$('iptMdes').value = qy[i].desc;
      	$('imgMTone').src = qy[i].imgurl;
      	$('imgMToneSmall').src = qy[i].imgurls;          
        
        console.log("showMTone id="+id);
        toPage('#pMToneAdd');    
    },function(){alert('selDB Milestone error!');}
    );    
};

//新建里程碑
function AddMTone(){
    Phone.mtoneid = 0;
    $('iptMday').value = getDateStr(0);
    $('iptMdes').value = '';
    $('imgMTone').src = 'none.png';
    $('imgMToneSmall').src = 'none.png';
      	    
    toPage('#pMToneAdd');
};

//保存里程碑
function saveMTone(){
     var idx = Phone.babyidx;
     
    var v1 = x$('#iptMday').attr('value').toString().replace(new RegExp("-","g"),"");
    var v2 = $('iptMdes').value;
    var img1 = x$('#imgMTone').attr('src');
    var img2 = x$('#imgMToneSmall').attr('src');
    //alert(v2);
    var vals = Phone.baby[idx]._babyid+","+v1+",'"+img1+"','"+img2+"','"+v2+"'";
    console.log(vals);
    
    var gid = Phone.mtoneid;
    if( gid <= 0 ){ //新建
        console.log('Add Mtone');
        Phone.app.newDB("Milestone",vals,function(){
            console.log('>>newDB ok');
            toPage('#pMTone');
        },function(){console.log('>>newDB error');}
        );        
    }else{ //编辑
        var sql = "UPDATE Milestone set addtime="+v1+",imgurl='"+img1+"',imgurls='"+img2+"',desc='"+v2+"'";
        sql += " WHERE _mtoneid="+gid;
        Phone.app.queryDB(sql, function(){
            console.log('>>editDB MTone ok');
            toPage('#pMTone');
        },function(){console.log('>>editDB pMTone error');}
        );         
    }    
};

/*************************************************
* Diary
* 日记
**************************************************/

function moreDiary(){
    var idx = Phone.babyidx;
    var bid = Phone.baby[idx]._babyid;
    var dsql = "select * from Diary where _babyid="+bid;
    dsql += " order by addtime desc limit "+Phone.diarylimit;
    dsql += " offset "+((Phone.diarypage)*Phone.diarylimit);
    //alert( dsql );
    ShowLoad(1);
    Phone.app.queryDB(dsql, function(q){
        console.log('>>queryDB Diary ok');
        ShowLoad(0);
        
		Phone.diary = eval(q);
		Phone.diarynum = Phone.diary.length;
		
		if( Phone.diarynum > 0){ Phone.diarypage++; }
	    else {if(hone.diarypage>0)Alert('日记已经读取完毕'); return;}
	        
		var ul = $("diary_list");
        var t=ul.childNodes.length;
        if( Phone.diaryupt ){
            Phone.diaryupt = false;
            for(i=0;i<t;i++) //移除li
                ul.removeChild(ul.childNodes[0]);
        }
		for(i=0;i<Phone.diarynum;i++){				    
		    var li2 = document.createElement("li");
		    li2.className = "li_ico diary_ico";
		    li2.innerHTML = "<img src='"+Phone.diary[i].imgurls+"'/>";
		    ul.appendChild(li2);			    
		    
		    var li3 = document.createElement("li");
		    li3.className = "li_cont";
		    li3.setAttribute("onclick", "showDiary("+Phone.diary[i]._diaryid+");"); 
		    txt = "<h1><span>"+getAge(Phone.diary[i].addtime)+"</span>"+ getDateStr(Phone.diary[i].addtime) +"</h1>";
		    li3.innerHTML = txt+"<p>"+Phone.diary[i].content+"</p>";
		    ul.appendChild(li3);
		}
		ShowLoad(0);      

    },function(){console.log('>>queryDB Diary error');}
    );    
    
}

//显示浏览或者编辑
function showDiaryEdit(b){
    x$('#edt_diary').setStyle('display','none');
    x$('#show_diary').setStyle('display','none');
    if(b){
        x$('#edt_diary').setStyle('display','block');
        x$('#btn_sharediary').setStyle('display','none');
        x$('#btn_editdiary').setStyle('display','none');
        x$('#btn_savediary').setStyle('display','inline');
        x$('#btn_backdiary').setStyle('display','none');
        x$('#btn_backdiary2').setStyle('display','inline');        
    }else{
        x$('#show_diary').setStyle('display','block');
        x$('#btn_sharediary').setStyle('display','inline');
        x$('#btn_editdiary').setStyle('display','inline');
        x$('#btn_savediary').setStyle('display','none');
        x$('#btn_backdiary').setStyle('display','inline');
        x$('#btn_backdiary2').setStyle('display','none');
    }
};

//显示日记
function showDiary(id){
    Phone.diaryid = id;
    Phone.app.selDB('diary','_diaryid='+id,function(q){
        var qy = eval(q);
        //编辑框
        $('iptDday').value = getDateStr(qy[0].addtime);
        $('iptDdes').value = qy[0].content;
        $('imgDiary').src = qy[0].imgurl;
        $('imgDiarySmall').src = qy[0].imgurls;
        //仅显示
        x$('#d_day').html(getDateStr(qy[0].addtime));
        x$('#d_content').html(qy[0].content);
        x$('#d_img').attr('src',qy[0].imgurl);;
        
        console.log("showDiary id="+id);
        toPage('#pDiaryAdd');
        showDiaryEdit(false);      
    },function(){alert('selDB diary error!');}
    );
};

//新建日记
function addDiary(){
    Phone.diaryid = 0;
    $('iptDday').value = getDateStr(0);
    $('iptDdes').value = "";
    $('imgDiary').src = "none.png";
    $('imgDiarySmall').src = "none.png";
   
    showDiaryEdit(true);
    
    x$('#btn_backdiary').setStyle('display','inline');
    x$('#btn_backdiary2').setStyle('display','none');    
    toPage('#pDiaryAdd');
};

//编辑日记
function editDiary(){
    showDiaryEdit(true);
};

//保存日记
function saveDiary(){
    var idx = Phone.babyidx;
     
    var v1 = x$('#iptDday').attr('value').toString().replace(new RegExp("-","g"),"");
    var v2 = $('iptDdes').value; //x$('#iptMdes').html();
    var img1 = x$('#imgDiary').attr('src');
    var img2 = x$('#imgDiarySmall').attr('src');
    //alert(v2);
    var vals = Phone.baby[idx]._babyid+","+v1+",'"+img1+"','"+img2+"','"+v2+"'";
    console.log(vals);
    
    var gid = Phone.diaryid;
    if( gid <= 0 ){ //新建
        console.log('Add Diary');
        Phone.app.newDB("Diary",vals,function(){
            console.log('>>newDB ok');
            toPage('#pDiary');
        },function(){console.log('>>newDB error');}
        );        
    }else{ //编辑
        var sql = "UPDATE Diary set addtime="+v1+",imgurl='"+img1+"',imgurls='"+img2+"',content='"+v2+"'";
        sql += " WHERE _diaryid="+gid;
        Phone.app.queryDB(sql, function(){
            console.log('>>editDB Diary ok');
            toPage('#pDiary');
        },function(){console.log('>>editDB Diary error');}
        );         
    }
    Phone.diaryupt = true;
    Phone.diarypage = 0;
};

//////////////////////////////////////////////////////////////////
//

//备份数据库
function backup(){
    if( Confirm('确定要备份数据库么?', function(){
        Phone.app.backupDB(function(){
            Alert('数据已经备份到SD卡(babyDiary/backup)!');
        },function(){
            Alert('备份数据库出现异常信息,确保安装了SD卡!');
        });        
    }, function(){}) );  
}

//恢复数据库
//func: 初次安装时检测
function restore(func){
    Phone.app.exists(Phone.env.dbbackuppath,function(){
        str ='确定要恢复已经备份的数据库么?';
        if(func!=null && func!="undefined")
            str = '检测到你重新安装了本应用,是否从SD卡恢复备份的数据库?';
        if( Confirm(str, function(){
            Phone.app.restoreDB(function(){
                alert('数据已经从SD卡恢复!\n请重新启动本软件!');
                navigator.app.exitApp();
            },function(){
                Alert('恢复数据库出现异常信息!');
            });        
        }, function(){if(func!=null && func!="undefined")func();}) );  
    },function(){
        if(func==null || func=="undefined")
            Alert('目前还没有备份数据库!');
        else
            func(); //
    });
}

//升级-反馈
function update(){
    var str = '感谢使用"宝宝成长日记"\n\n请发邮件到:\n'+Phone.email;
    Alert( str );
    //location.href = Phone.site;
}
//关于
function about(){
    var str = "      宝宝成长日记\n版本: "+Phone.version_des+"\n作者: "+Phone.author+"\n"+Phone.site;
    //if(Phone.appno!='undefined') str += '\n编号: '+Phone.appno;
    Alert( str );
}

//皮肤
function skin(){
    x$('#skin').setStyle('display', 'block');
    x$('#mask').setStyle('display', 'block');
}
function setSkin(id){
    x$('#skin').setStyle('display', 'none');
    x$('#mask').setStyle('display', 'none');
    
    x$('link').each(function(ele,idx){
        if( ele.id.toString().indexOf('skin')>=0 ){
            if( ele.id == id ){
                ele.disabled = false;
                window.localStorage.setItem("skin", ele.id.toString());
            }else{
                ele.disabled = true;
            }
        }
    });
}
function loadSkin(){
    return window.localStorage.getItem("skin");
}

</script>
</head>
<body>
<!--loading-->
<div id="load">正在读取中...</div>
<!--mask-->
<div id="mask" class="hide"></div>

<!--底部导航栏-->
<ul class="nav_foot" id="nav_foot">
<li class="grow" uiTo="#pGrow">&nbsp</li>
<li class="mtone" uiTo="#pMTone">&nbsp</li>
<li class="home_fcs" uiTo="#pHome">&nbsp</li>
<li class="diary" uiTo="#pDiary">&nbsp</li>
<li class="set" id="log1" uiTo="#pTools">&nbsp</li>
</ul>
<!--/底部导航栏-->

<!--首页-->
<div id="pHome" class="page">
<div class="head"><h1>宝宝成长日记</h1></div>
<div id="bbInfo">
<div id="bbImg" onclick="toPage('#pBaby')"></div>
<ul>
<li id="bbName">Baby</li>
<li id="bbBir">dddd</li>
<li id="bbAge"></li>
</ul>
</div>
<!--
<div id="bbAdd"> </div>
//-->
<ul id="bbGrid">
<li class="b1">
<h1>身高 体重</h1>
<table width="100%" border="0">
<tr><td id="bbH" onclick="AddGrow();">点击新建</td><td id="bbW" > </td></tr>
<tr><td id="bbHt"></td><td id="bbWt"> </td></tr>
</table>
</li>
<li class="b2">
<h1>头围 胸围</h1>
<table width="100%" border="0">
<tr><td id="bbHd" onclick="AddGrow();">点击新建</td><td id="bbC"> </td></tr>
<tr><td id="bbHdt"></td><td id="bbCt"> </td></tr>
</table>
</li>
<li class="b3">
<h1>里程碑</h1>
<table width="100%" border="0">
<tr><td height="55"><div id="bbM" onclick="AddMTone();">点击新建</div></td></tr>
<tr><td id="bbMt"></td></tr>
</table>
</li>
<li class="b4">
<h1>日 记</h1>
<table width="100%" border="0">
<tr><td height="55"><div id="bbD" onclick="addDiary();">点击新建</div></td></tr>
<tr><td id="bbDt"> </td></tr>
</table>
</li>
</ul>

<div style="text-align:center;font-size:10px;line-height:25px;">宝宝成长日记 &copy; 2012</div>

</div>
<!--/首页-->

<!--编辑宝宝-->
<div id="pBaby" class="page hide">
<div class="head"><h1>宝宝信息</h1></div>
<!--main-->
<div class="main">

<ul class="form_list">
<li><h3>姓名</h3><input type="text" id="iptName" value=""/></li>
<li><h3>性别</h3><input type="text" id="iptSex" value="" readonly="true" onclick="getSex(this)"/></li>
<li><h3>生日</h3><input type="text" id="iptBir" value="" readonly="true" onclick="getBirthday(this)"/></li>
<li><h3>头像</h3><img id="imgSrc" src="" width="100" height="100" onclick="getHeadimg(this)"/></li>
</ul>
<div class="btns">
<button onclick="saveBaby()">保存</button><button onclick="abortBaby()">返回</button>
</div>

</div>
<!--end main-->
</div>
<!--/编辑宝宝-->

<!--成长数据-->
<div id="pGrow" class="page hide">
<div class="head"><a href="javascript:AddGrow()">+新建+</a><h1>成长数据</h1></div>
<ul class="tab_nav">
<li class="fcs" id="gnav1" onclick="growtab(1)">成长曲线</li><li class="nor" id="gnav2" onclick="growtab(2)">历史记录</li><li class="nor" id="gnav3" onclick="growtab(3)">参考标准</li>
</ul>
<!--main-->
<div class="clear"></div>
<div class="main">

<!-- 统计绘图区域 -->
<div id="grow_tab1">
<canvas id="grow_canvas1" width="295" height="190"></canvas>
<br/>
<canvas id="grow_canvas2" width="295" height="180"></canvas>
</div>
<div id="grow_tab3" class="hide" style="text-align:center"><img src="data/bz.png" /></div>

<!--list-->
<ul class="list2 hide" id="grow_tab2">
<!--
<li class="arrow"><img src="none.png"/><h1>高(76)重(9.8)头(56)胸(48)</h1><p>日期: 2011-11-10 7个月</p></li>
-->
</ul>
<!--end list-->

</div>
</div>
<!--/成长数据-->

<!--编辑身体数据-->
<div id="pGrowAdd" class="page hide">
<div class="head"><h1>记录身体数据</h1></div>
<!--main-->
<div class="main">

<ul class="form_list">
<li><h3>统计日期</h3><input type="text" id="iptGday" value="" readonly="true" onclick="getBirthday(this)"/></li>
<li><h3>身高(厘米)</h3><input type="number" min="0" max="200" id="iptHt" value="0" /></li>
<li><h3>体重(斤)</h3><input type="number" id="iptWt" min="0" max="100" value="0" /></li>
<li><h3>头围(厘米)</h3><input type="number" id="iptHd" min="0" max="100" value="0" /></li>
<li><h3>胸围(厘米)</h3><input type="number" id="iptCt" min="0" max="100" value="0" /></li>
<li><h3>照 片</h3><input type="button" value="" class="btn_tk" onclick="getPic(0,'#imgGrow')" />&nbsp;&nbsp<input type="button" value="" class="btn_xj" onclick="getPic(1,'#imgGrow')" /></li>
<li><h3><img id="imgGrowSmall" width="45" height="45" src="none.png"/></h3><img id="imgGrow" src="none.png"/></li>
</ul>

<div class="btns">
<button onclick="saveGrow()">保存</button><button onclick="Back();">返回</button>
</div>
<div class="clear"></div>
<p>如果某个参数没有测量,请输入 0</p>

</div>
<!--end main-->
</div>
<!--/编辑身体数据-->

<!--里程碑-->
<div id="pMTone" class="page hide">
<div class="head"><a href="javascript:AddMTone()">+新建+</a><h1>里程碑</h1></div>
<!--main-->
<div class="clear"></div>
<div class="main">
<!--list-->
<ul class="list2" id="mtone_list">
<!--
<li class="arrow"><p>日期: 2011-11-10 7个月</p><img src="none.png"/><h1>宝宝长牙了</h1></li>
-->
</ul>
<!--end list-->
</div>
</div>
<!--/里程碑-->

<!--编辑里程碑-->
<div id="pMToneAdd" class="page hide">
<div class="head"><h1>记录里程碑</h1></div>
<!--main-->
<div class="main">

<ul class="form_list">
<li><h3>日期</h3><input type="text" id="iptMday" value="" readonly="true" onclick="getBirthday(this)"/></li>
<li><h3>事件</h3><textarea id="iptMdes" rows="6">  </textarea></li>
<li><h3>照 片</h3><input type="button" value="" class="btn_tk" onclick="getPic(0,'#imgMTone')" />&nbsp;&nbsp<input type="button" value="" class="btn_xj" onclick="getPic(1,'#imgMTone')" /></li>
<li><h3><img id="imgMToneSmall" width="45" height="45" src="none.png"/></h3><img id="imgMTone" src="none.png"/></li>
</ul>

<div class="btns">
<button onclick="saveMTone()">保存</button><button onclick="Back();">返回</button>
</div>

</div>
<!--end main-->
</div>
<!--/编辑里程碑-->

<!--日记-->
<div id="pDiary" class="page hide">
<div class="head"><a href="javascript:addDiary()">+新建+</a><h1>日记</h1></div>
<!--main-->
<div class="clear"></div>
<div class="main">
<!--list-->
<ul class="list2" id="diary_list">
<!--
<li class="li_ico diary_ico"><img src="none.png"/></li><li class="li_cont"><h1><span>7个月</span>2011-11-10</h1><p>hhh</p></li>
<li class="li_ico diary_ico"><img src="none.png"/></li><li class="li_cont"><h1><span>7个月</span>2011-11-10</h1><p>hhh</p></li>
-->
</ul>
<!--end list-->
<div style="text-align:center;">
<button onclick="moreDiary()">查看更多</button>
</div>
</div>
</div>
<!--/日记-->

<!--编辑日记-->
<div id="pDiaryAdd" class="page hide">
<div class="head"><h1>日记</h1></div>
<!--main-->
<div class="main">

<ul class="form_list" id="edt_diary">
<li><h3>日期</h3><input type="text" id="iptDday" value="" readonly="true" onclick="getBirthday(this)"/></li>
<li><textarea id="iptDdes" rows="16"></textarea></li>
<li><h3>照片</h3><input type="button" value="" class="btn_tk" onclick="getPic(0,'#imgDiary')" />&nbsp;&nbsp;<input type="button" value="" class="btn_xj" onclick="getPic(1,'#imgDiary')" /></li>
<li><h3><img id="imgDiarySmall" width="45" height="45" src="none.png"/></h3><img id="imgDiary" src="none.png"/></li>
</ul>

<ul class="content_list" id="show_diary">
<li><h3 id="d_day">日期</h3></li>
<li><p id="d_content"></p></li>
<li><img src="none.png" id="d_img"/></li>
</ul>

<div class="btns">
<button onclick="share('d_day','宝宝日记','d_content','d_img');" id="btn_sharediary">分享</button><button onclick="editDiary();" id="btn_editdiary">编辑</button><button onclick="saveDiary();" id="btn_savediary" >保存</button><button onclick="Back()" id="btn_backdiary">返回</button><button onclick="showDiaryEdit(false)" id="btn_backdiary2">返回</button>
</div>

</div>
<!--end main-->
</div>
<!--/编辑日记-->

<!--工具-->
<div id="pTools" class="page hide">
<div class="head"><h1>工具</h1></div>
<!--main-->
<div class="clear"></div>
<div class="main">
<!--list-->
<ul class="list" id="set_list">
<li class="arrow" onclick="skin();"><img src="none.png"/><h1>更换皮肤</h1><p>选择你喜欢的一款皮肤</p></li>
<li class="arrow" onclick="backup();"><img src="none.png"/><h1>数据库备份</h1><p>备份您的数据到存储卡上</p></li>
<li class="arrow" onclick="restore(null);"><img src="none.png"/><h1>数据库恢复</h1><p>从存储卡恢复您上次备份的数据</p></li>
<li class="arrow" onclick="about();"><img src="none.png"/><h1>关于软件</h1><p>关于宝宝成长日记的信息</p></li>
<li class="arrow" onclick="update();"><img src="none.png"/><h1>反馈信息</h1><p>有问题或者建议请反馈给作者</p></li>
</ul>
<!--end list-->
</div>
</div>
<!--/工具-->

<div id="skin" class="dlg hide">
<ul>
<li onclick="setSkin('')"><img src="data/bg_s.png" width="20" height="20"/><p>蓝色经典</p></li>
<li onclick="setSkin('skin_2')"><img src="data/bg2_s.png" width="20" height="20"/><p>粉红心情</p></li>
<li onclick="setSkin('skin_3')"><img src="data/bg3_s.png" width="20" height="20"/><p>新年快乐</p></li>
<li onclick="setSkin('skin_4')"><img src="data/bg4_s.png" width="20" height="20"/><p>龙宝宝</p></li>
</ul>
</div>
</body>
</html>
